<template>
  <view class="content">
    <!-- 状态栏 -->
<!--    <view class="navbar" style="background-color: #f5f5f5; width: 100%;height: var(&#45;&#45;status-bar-height);">-->
<!--    </view>-->

    <!-- 搜索头部 - 添加动态定位样式 -->
    <view class="search-header" :style="{position:headerPosition,top:headerTop}">
      <!-- 返回按钮 -->
      <view class="back-btn" @click="goBack">
        <image src="../..//static/images/back.png" class="back-icon"></image>
      </view>

      <!-- 搜索输入框 -->
      <view class="search-input-container">
        <view class="search-input-box">
          <input
              type="text"
              :placeholder="defaultKeyword"
              @input="inputChange"
              v-model="keyword"
              @confirm="doSearch(false)"
              placeholder-class="placeholder-class"
              confirm-type="search"
              class="search-input"
          >
        </view>
      </view>

      <!-- 搜索按钮 -->
      <view class="search-text-btn" @click="search()">搜索</view>
    </view>

    <!-- 搜索推荐内容 -->
    <view class="search-content" @touchstart="blur">
      <!-- 动态关键词列表 -->
      <scroll-view class="keyword-list-box" v-show="isShowKeywordList" scroll-y>
        <view class="keyword-entry" hover-class="keyword-entry-tap" v-for="row in keywordList" :key="row.keyword">
          <view class="keyword-text" @tap="doSearch(row.keyword)">
            <rich-text :nodes="row.htmlStr"></rich-text>
          </view>
          <view class="keyword-img" @tap="setkeyword(row)">
            <image src="/static/HM-search/back.png"></image>
          </view>
        </view>
      </scroll-view>

      <!-- 搜索推荐区域 -->
      <view class="recommend-section" v-show="!isShowKeywordList">
        <!-- 搜索推荐标题 -->
        <view class="recommend-title">搜索推荐</view>

        <!-- 推荐标签网格 -->
        <view class="recommend-tags">
          <view
              class="tag-item"
              v-for="(tag, index) in recommendTags"
              :key="index"
              @tap="doSearch(tag)"
          >
            {{ tag }}
          </view>
        </view>

        <!-- 历史搜索 -->
        <view class="history-section" v-if="oldKeywordList.length > 0">
          <view class="history-header">
            <view class="history-title">历史搜索</view>
            <view class="clear-btn" @tap="oldDelete">
              <image src="/static/HM-search/delete.png" class="clear-icon"></image>
            </view>
          </view>
          <view class="history-tags">
            <view
                v-for="(keyword, index) in oldKeywordList"
                @tap="doSearch(keyword)"
                :key="index"
                class="history-tag"
            >
              {{ keyword }}
            </view>
          </view>
        </view>
      </view>
    </view>
  </view>
</template>

<script>
export default {
  data() {
    return {
      // 添加动态定位相关数据
      headerPosition: "fixed",
      headerTop: "0px",

      defaultKeyword: "搜索更多智能产品",
      keyword: "",
      oldKeywordList: [],
      keywordList: [],
      isShowKeywordList: false,
      // 推荐搜索标签
      recommendTags: [
        '家防', '照明', '插座开关', '传感器',
        '影音娱乐', '环境电器', '路由网关',
        '厨房电器'
      ]
    }
  },
  onLoad() {
    // 参考list.vue的处理方式
    // #ifdef H5
    this.headerTop = document.getElementsByTagName('uni-page-head')[0].offsetHeight+'px';
    // #endif

    this.init();
  },
  // 添加页面滚动监听
  onPageScroll(e){
    // 兼容iOS端下拉时顶部漂移
    if(e.scrollTop >= 0){
      this.headerPosition = "fixed";
    } else {
      this.headerPosition = "absolute";
    }
  },
  methods: {
    init() {
      this.loadDefaultKeyword();
      this.loadOldKeyword();
    },

    // 返回上一页
    goBack() {
      uni.navigateBack({
        delta: 1
      });
    },

    blur() {
      uni.hideKeyboard()
    },

    //加载默认搜索关键字
    loadDefaultKeyword() {
      this.defaultKeyword = "搜索更多智能产品";
    },

    //加载历史搜索,自动读取本地Storage
    loadOldKeyword() {
      uni.getStorage({
        key: 'OldKeys',
        success: (res) => {
          var OldKeys = JSON.parse(res.data);
          this.oldKeywordList = OldKeys;
        }
      });
    },

    //监听输入
    inputChange(event) {
      var keyword = event.detail ? event.detail.value : event;
      if (!keyword) {
        this.keywordList = [];
        this.isShowKeywordList = false;
        return;
      }
      this.isShowKeywordList = true;

      // 模拟搜索建议
      if (requestTask) {
        requestTask.abort();
      }

      var requestTask = uni.request({
        url: 'https://suggest.taobao.com/sug?code=utf-8&q=' + keyword,
        success: (res) => {
          this.keywordList = this.drawCorrelativeKeyword(res.data.result, keyword);
        }
      });
    },

    //高亮关键字
    drawCorrelativeKeyword(keywords, keyword) {
      let keywordArr = [];
      if (keywords && keywords.length) {
        for (let i = 0; i < keywords.length; i++) {
          let row = keywords[i];
          let html = row[0].replace(keyword, "<span style='color: #999;'>" + keyword + "</span>");
          html = '<div>' + html + '</div>';
          let tmpObj = {
            keyword: row[0],
            htmlStr: html
          };
          keywordArr.push(tmpObj)
        }
      }
      return keywordArr;
    },

    //顶置关键字
    setkeyword(data) {
      this.keyword = data.keyword;
    },

    //清除历史搜索
    oldDelete() {
      uni.showModal({
        content: '确定清除历史搜索记录？',
        success: (res) => {
          if (res.confirm) {
            this.oldKeywordList = [];
            uni.removeStorage({
              key: 'OldKeys'
            });
          }
        }
      });
    },

    //执行搜索
    doSearch(key) {
      key = key ? key : this.keyword ? this.keyword : this.defaultKeyword;
      this.keyword = key;
      this.saveKeyword(key);
      uni.navigateTo({
        url: `/pages/search/list?keyword=${key}`
      })
    },

    search() {
      this.doSearch()
    },

    //保存关键字到历史记录
    saveKeyword(keyword) {
      uni.getStorage({
        key: 'OldKeys',
        success: (res) => {
          var OldKeys = JSON.parse(res.data);
          var findIndex = OldKeys.indexOf(keyword);
          if (findIndex == -1) {
            OldKeys.unshift(keyword);
          } else {
            OldKeys.splice(findIndex, 1);
            OldKeys.unshift(keyword);
          }
          OldKeys.length > 10 && OldKeys.pop();
          uni.setStorage({
            key: 'OldKeys',
            data: JSON.stringify(OldKeys)
          });
          this.oldKeywordList = OldKeys;
        },
        fail: (e) => {
          var OldKeys = [keyword];
          uni.setStorage({
            key: 'OldKeys',
            data: JSON.stringify(OldKeys)
          });
          this.oldKeywordList = OldKeys;
        }
      });
    }
  }
}
</script>

<style lang="scss">
.content {
  background-color: #f5f5f5;
  min-height: 100vh;
  // 参考list.vue的padding-top设置，并向下调整
  padding-top: 90rpx;
}

/* 搜索头部 - 修改为支持动态定位，参考list.vue的navbar样式 */
.search-header {
  position: fixed; // 默认固定定位
  left: 0;
  width: 100%;
  background-color: #f5f5f5;
  padding: 40rpx 30rpx 0 30rpx;
  display: flex;
  align-items: center;
  gap: 20rpx;
  padding-top: 80rpx; // 增加顶部间距，向下调整位置
  z-index: 10; // 添加层级
  box-shadow: 0 2rpx 10rpx rgba(0,0,0,.06); // 添加阴影效果

  .back-btn {
    width: 60rpx;
    height: 60rpx;
    display: flex;
    align-items: center;
    justify-content: center;

    .back-icon {
      width: 40rpx;
      height: 40rpx;
    }
  }

  .search-input-container {
    flex: 1;

    .search-input-box {
      background-color: #ffffff;
      border-radius: 30rpx;
      padding: 0 30rpx;
      height: 60rpx;
      display: flex;
      align-items: center;

      .search-input {
        width: 100%;
        height: 100%;
        font-size: 28rpx;
        border: none;
        outline: none;
      }
    }
  }

  .search-text-btn {
    color: #09BB07;
    font-size: 28rpx;
    font-weight: 500;
    padding: 0 10rpx;
  }
}

.placeholder-class {
  color: #999;
  font-size: 28rpx;
}

/* 搜索内容区域 */
.search-content {
  background-color: #ffffff;
  margin-top: 20rpx;
  min-height: calc(100vh - 120rpx);
}

/* 推荐搜索区域 */
.recommend-section {
  padding: 40rpx 30rpx;

  .recommend-title {
    font-size: 32rpx;
    font-weight: bold;
    color: #333;
    margin-bottom: 30rpx;
  }

  .recommend-tags {
    display: flex;
    flex-wrap: wrap;
    gap: 20rpx;
    margin-bottom: 50rpx;

    .tag-item {
      background-color: #f8f8f8;
      color: #666;
      font-size: 28rpx;
      padding: 20rpx 30rpx;
      border-radius: 25rpx;
      border: 1rpx solid #e8e8e8;
      transition: all 0.2s ease;

      &:active {
        background-color: #e8e8e8;
        transform: scale(0.95);
      }
    }
  }
}

/* 历史搜索区域 */
.history-section {
  .history-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 30rpx;

    .history-title {
      font-size: 32rpx;
      font-weight: bold;
      color: #333;
    }

    .clear-btn {
      padding: 10rpx;

      .clear-icon {
        width: 32rpx;
        height: 32rpx;
      }
    }
  }

  .history-tags {
    display: flex;
    flex-wrap: wrap;
    gap: 20rpx;

    .history-tag {
      background-color: #f8f8f8;
      color: #666;
      font-size: 28rpx;
      padding: 20rpx 30rpx;
      border-radius: 25rpx;
      border: 1rpx solid #e8e8e8;
      transition: all 0.2s ease;

      &:active {
        background-color: #e8e8e8;
        transform: scale(0.95);
      }
    }
  }
}

/* 关键词列表 */
.keyword-list-box {
  background-color: #ffffff;
  max-height: calc(100vh - 140rpx);

  .keyword-entry {
    width: 94%;
    margin: 0 3%;
    padding: 30rpx 0;
    font-size: 30rpx;
    color: #333;
    display: flex;
    justify-content: space-between;
    align-items: center;
    border-bottom: 1rpx solid #f0f0f0;

    .keyword-text {
      flex: 1;
    }

    .keyword-img {
      width: 60rpx;
      height: 60rpx;
      display: flex;
      align-items: center;
      justify-content: center;

      image {
        width: 40rpx;
        height: 40rpx;
      }
    }

    &:active {
      background-color: #f8f8f8;
    }
  }
}
</style>